package com.xiaolin.login.controller;

import com.xiaolin.login.model.Member;
import com.xiaolin.login.service.MemberService;
import com.xiaolin.login.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/10/7
 * @Version 1.0
 */
@Controller
@RequestMapping("/sso")
public class LoginController {
    @Autowired
    MemberService memberService;

    /**
     * 统一登录
     * @param member
     * @param session
     * @param response
     * @return
     */
    @PostMapping("/login")
    public String login(Member member, HttpSession session, HttpServletResponse response){
        String redirect = (String) session.getAttribute("redirect");
        if(member !=null && !StringUtils.isEmpty(member.getUsername()) && !StringUtils.isEmpty(member.getPassword())){
            Member user = memberService.selectByName(member.getUsername());
            if(user!=null && user.getPassword().equals(member.getPassword())){
                //生成token
                String token = UUID.randomUUID().toString();
                Cookie cookie=new Cookie("token",token);
                //设置cookie的域名为顶级域名
                cookie.setDomain("ssologin.com");
                response.addCookie(cookie);
                //将token与用户信息存储到缓存中
                TokenUtils.cache.put(token,user);
                return "redirect:"+redirect;
            }
        }
        return "login";
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/getUserInfo")
    public ResponseEntity<Member> getUserInfo(@RequestParam("token") String token){
        if(!StringUtils.isEmpty(token)){
            Member user = (Member) TokenUtils.cache.get(token);
            return new ResponseEntity<Member>(user,null);
        }
        return null;
    }

    @GetMapping("/logout")
    public String logout(@CookieValue(required = false,value = "token") Cookie cookie, HttpSession session){
        String redirect = (String) session.getAttribute("redirect");
        if(cookie !=null){
            cookie.setMaxAge(0);
        }
        TokenUtils.cache.clear();
        return "redirect:"+redirect;
    }
}
